package com.fenghongzhang.day015;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;

import java.util.ArrayList;
import java.util.List;

public class MusicUtil {

    /**
     * 返回适配器的数据源
     *
     */
    public static List<Music> getMusic(Context context){
        List<Music> list = new ArrayList<>();
        //会->添加数据源
        ContentResolver contentResolver = context.getContentResolver();
        Cursor query = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        if(query != null){
            while(query.moveToNext()){
                String title = query.getString(query.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String artist = query.getString(query.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String duration = query.getString(query.getColumnIndex(MediaStore.Audio.Media.DURATION));
                String data = query.getString(query.getColumnIndex(MediaStore.Audio.Media.DATA));

                //过滤短音频
                if(Integer.parseInt(duration) < 60 * 1000){
                    continue;
                }

                Music music = new Music();
                music.setTitle(title);
                music.setArtist(artist);
                music.setDuration(duration);
                music.setData(data);
                list.add(music);
            }
            //记得关闭
            query.close();
        }
        return list;
    }

    //3:15  3:9 -> 3:09
    public static String fmtTime(String time){
        int i = Integer.parseInt(time);
        if ((i / 1000 % 60) < 10){ // 0-9
           return (i / 1000 / 60 +":0" + i / 1000 % 60);
        }else{
            return (i / 1000 / 60 +":" + i / 1000 % 60);
        }
    }
}
